import axios from 'axios';
import { api } from '../../common/baseConfig';
import { message } from 'antd';
import NProgress from 'nprogress';
import { delCookie } from './cookies';
import $ from 'jquery';
let service = axios.create({
  baseURL: api,
  timeout: 10000,
  withCredentials: true,
});
//添加请求拦截器
service.interceptors.request.use(
  function(config) {
    if (
      config.url.endsWith('SubmitPraticeQuestion') ||
      config.url.endsWith('SaveCourse_Look')
    ) {
      return config;
    }
    if (config.url.endsWith('QueryOrder')) {
      let token = localStorage.getItem('payToken');
      config.headers.common['Authorization'] = 'Bearer ' + token;
      return config;
    }
    NProgress.start();
    return config;
  },
  function(error) {
    return Promise.reject(error);
  },
);
//添加响应拦截器
service.interceptors.response.use(
  function(response) {
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
     */
    RequestCodeStatus(response);
    //错误信息汇报
    NProgress.done();

    return response;
  },
  function(error) {
    console.error('err' + error);
    message.error('网络异常，请稍后再试');
    return Promise.reject(error);
  },
);
export default {
  //get请求
  get(obj) {
    return service({
      method: 'get',
      url: obj.url,
      params: obj.params,
    });
  },
  //post 请求
  post(obj) {
    return service({
      method: 'post',
      url: obj.url,
      data: obj.params,
    });
  },
  postAjax(obj) {
    obj.url = api + obj.url;
    obj.type = 'post';
    obj.async = false;
    // obj.processData = false;
    $.ajax(obj);
  },
};
function RequestCodeStatus(response) {
  const { SuccessResponse, ResponseCode, Message } = response.data;
  if (!SuccessResponse) {
    if (Message === '没有更多的试题') {
      message.warn(Message);
      return response;
    }
    if (ResponseCode !== 403) {
      message.error(Message);
    }
  }
  if (
    ResponseCode === 403 &&
    localStorage.getItem('needSys403Warn') === 'true'
  ) {
    localStorage.setItem('needSys403Warn', false);
    localStorage.setItem('showLoginModal', true);
    window.$flag = false;
    message.warn('网站未登录，请登录');
    delCookie('UserKey');
    delCookie('sessionId');
    delCookie('UserPhoneKey');
    delCookie('UserNameKey');
    localStorage.removeItem('studentinfo');
    // window.location.href = "/login";
  }
}
